package edu.corn.job.core.processor;

import edu.corn.job.core.context.JobRunningContext;
import edu.corn.job.core.processor.adapter.handler.CheckAndDoneHandler;

import java.util.ArrayList;
import java.util.List;

import static edu.corn.job.core.processor.adapter.handler.CheckAndDoneHandler.DONE;

public abstract class AbstractCompositeJob extends AbstractJobProcessor {

    /**
     * 级联或组合job的控制器。
     */
    private CheckAndDoneHandler compositeHandler;

    private final List<AbstractJobProcessor> children = new ArrayList<>();

    public void registerHandler(CheckAndDoneHandler handler) {
        compositeHandler = handler;
    }

    protected void registerChild(AbstractJobProcessor processor) {
        children.add(processor);
    }

    protected void registerChild(AbstractCompositeJob processor, CheckAndDoneHandler handler) {
        processor.registerHandler(handler);
        children.add(processor);
    }

    @Override
    public void execute(JobRunningContext context) {
        // 什么也不做，可以做日志记录等。将具体的操作下沉至Phase。
    }

    @Override
    public List<AbstractJobProcessor> children() {
        return children;
    }


    @Override
    public String checkAndDone(JobRunningContext context) {
        // 组合式的job检查当前组合内的结果是否正确或者是否有异常，有的话是否需要重试等。
        if (compositeHandler != null) {
            return compositeHandler.handle(context);
        }
        return DONE;
    }


}
